package com.supply.dl.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import butterknife.BindView;
import butterknife.OnClick;

import com.bigkoo.pickerview.TimePickerView;
import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalAdapter;
import com.supply.dl.app.adapter.RecyclerViewDivider;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.NormalObserver;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.FilterParentBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.request.SearchStockRequest;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.DialogUtils;
import com.supply.dl.utils.StringUtils;

import io.reactivex.Observable;
import io.reactivex.functions.Function3;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库位选择页(三条件排序的选择页)
 * <p>
 * Author: tian <br>
 * Time: 2018/4/28 10:27
 */
public class DepotSelectActivity extends BaseActivity {
    public static final int TYPE_ALL = 0;
    public static final int TYPE_IN_STOCK = 1;//入库定位
    public static final int TYPE_OUT_STOCK = 2;//出库定位

    /**
     * 数据展示rv
     */
    @BindView(R.id.search_rv)
    RecyclerView search_rv;

    /**
     * 排序布局
     */
    @BindView(R.id.sort_ly)
    LinearLayout sort_ly;

    /**
     * 筛选rv
     */
    @BindView(R.id.filter_rv)
    RecyclerView filter_rv;

    /**
     * 筛选项
     */
    @BindView(R.id.common_search_main_filterTv)
    TextView common_search_main_filterTv;

    /**
     * 输入框
     */
    @BindView(R.id.common_search_main_searchContentEdt)
    EditText searchContentEdt;

    /**
     * 筛选试图布局
     */
    @BindView(R.id.filter_ly)
    RelativeLayout filter_ly;

    /**
     * 筛选按钮布局
     */
    @BindView(R.id.common_search_main_filterLayout)
    LinearLayout filter_btn_Layout;

    /**
     * 建单结束时间
     */
    @BindView(R.id.end_time_tv)
    TextView end_time_tv;

    /**
     * 建单起点时间
     */
    @BindView(R.id.start_time_tv)
    TextView start_time_tv;

    /**
     * 当前关键字
     */
    private String keyWord = "";

    /**
     * 当前用户选择的 筛选条件
     */
    private ArrayMap<String, String> filerMaps;

    /**
     * 筛选列表适配器
     */
    private NormalAdapter<FilterParentBean> filterAdapter;

    /**
     * 筛选数据来源
     */
    private ArrayList<FilterParentBean> filterDatas;

    /**
     * 开始和时间pickerview
     */
    private TimePickerView startPicker, endPicker;

    /**
     * 搜索页显示的数据
     */
    private List<SearchStockBean> resource;

    /**
     * 搜索页适配器
     */
    private NormalAdapter<SearchStockBean> adapter;

    /**
     * 物料编码和 title名字,仓库id
     */
    private String skuId, tilteName, whId;
    /**
     * 库存查询界面传过来的请求数据
     */
    private SearchStockRequest stockRequest;
    /**
     * 当前用户选中的 库存对象
     */
    private SearchStockBean currentSSb;

    private int showType = TYPE_ALL;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_depot_select;
    }

    @Override
    protected void initView() {

        if (getIntent().hasExtra("skuId"))
            skuId = getIntent().getStringExtra("skuId");
        if (getIntent().hasExtra("tilteName"))
            tilteName = getIntent().getStringExtra("tilteName");
        if (getIntent().hasExtra("whId"))
            whId = getIntent().getStringExtra("whId");
        if (getIntent().hasExtra("searchBean"))
            stockRequest = (SearchStockRequest) getIntent().getSerializableExtra("searchBean");

        if (getIntent().hasExtra("showType")) {
            showType = getIntent().getIntExtra("showType", TYPE_ALL);
        }

        setTitleShow(StringUtils.isCanUse(tilteName) ? tilteName : "库位选择");

        showLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (currentSSb == null) {
                    finish();
                    return;
                }

                DialogUtils.showDialog(DepotSelectActivity.this, "提示", "确定选择吗?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onSureSelect();
                    }
                }).show();

            }
        });

        resource = new ArrayList<>();

        adapter = new NormalAdapter<SearchStockBean>(this, resource) {
            @Override
            protected void convert(ViewHolder holder, SearchStockBean data) {
                ImageView status_ic = holder.getView(R.id.status_ic);
                if (stockRequest == null)
                    status_ic.setVisibility(View.VISIBLE);
                else
                    status_ic.setVisibility(View.GONE);
                if (data.isCheck()) {
                    status_ic.setImageResource(R.mipmap.check_selected);
                } else {
                    status_ic.setImageResource(R.mipmap.check_normal);
                }

                if (showType == TYPE_IN_STOCK) {
                    holder.getView(R.id.sku_code).setVisibility(View.GONE);
                    holder.getView(R.id.sku_name).setVisibility(View.GONE);
                    holder.getView(R.id.kc_type_tv).setVisibility(View.GONE);
                    holder.getView(R.id.guige_tv).setVisibility(View.GONE);
                    holder.getView(R.id.kc_status_tv).setVisibility(View.GONE);
                    holder.getView(R.id.pichi_num_tv).setVisibility(View.GONE);
                    holder.getView(R.id.car_number).setVisibility(View.VISIBLE);

                    holder.setText(R.id.wlck_tv, "入库物料库存:" + data.getAvailableInWeight());
                } else if (showType == TYPE_OUT_STOCK) {
                    holder.getView(R.id.sku_code).setVisibility(View.GONE);
                    holder.getView(R.id.sku_name).setVisibility(View.GONE);
                    holder.getView(R.id.car_number).setVisibility(View.VISIBLE);
                    holder.getView(R.id.ke_number).setVisibility(View.GONE);

                    holder.setText(R.id.wlck_tv, "物料库存:" + data.getAvailableInventoryTon());
                } else {
                    holder.setText(R.id.wlck_tv, "物料库存:" + data.getWeight());
                }

                holder.setText(R.id.sku_code, "物料编码:" + data.getSkuCode());
                holder.setText(R.id.sku_name, "物料名称:" + data.getSkuName());
                holder.setText(R.id.ck_name_tv, "仓库名称:" + data.getWhName());
                holder.setText(R.id.ck_code_tv, "仓库编码:" + data.getWhCode());
                holder.setText(R.id.cw_name_tv, "库位名称:" + data.getStockName());

                holder.setText(R.id.kc_type_tv, "库存类型:" + data.getStockTypeName());
                holder.setText(R.id.kc_status_tv, "库存状态:" + data.getStockStatusName());
                holder.setText(R.id.guige_tv, "规  格:" + data.getUnitName());
                holder.setText(R.id.pichi_num_tv, "批次号:" + data.getBatchNo());
                holder.setText(R.id.ke_number, "可入数量:" + data.getAvailableInAmount() + "件/"
                    + data.getAvailableInWeight() + "吨/" +data.getAvailableInVolume() + "方");
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_library_select;
            }
        };

        adapter.setOnItemClickListener(new NormalAdapter.OnItemClickListener<SearchStockBean>() {
            @Override
            public void onItemClick(ViewHolder viewHolder, SearchStockBean data, int position) {

                for (SearchStockBean stb : resource) {
                    if (stb.getId().equals(data.getId())) {
                        data.setCheck(!data.isCheck());
                        if (data.isCheck())
                            currentSSb = data;
                        else
                            currentSSb = null;
                        continue;
                    }
                    stb.setCheck(false);
                }

                adapter.notifyDataSetChanged();
            }
        });

        search_rv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        search_rv.setLayoutManager(new LinearLayoutManager(this));
        search_rv.setAdapter(adapter);
        searchContentEdt.setHint("仓库名称，代码，批次号");

        setRightInVisible();
        searchStock();

        initFilterLy();
    }

    /**
     * 初始化 筛选布局
     */
    private void initFilterLy() {
        //注意默认按钮是未选中
        filter_btn_Layout.setTag(false);

        filterDatas = new ArrayList<>();
        filterAdapter = new NormalAdapter<FilterParentBean>(this, filterDatas) {
            @Override
            protected void convert(ViewHolder holder, FilterParentBean data) {
                holder.setText(R.id.parent_name_tv, data.getName());
                RecyclerView item_filter_rv = holder.getView(R.id.item_filter_rv);
                final NormalAdapter<SelectDictionaryBean> itemAdapter = new NormalAdapter<SelectDictionaryBean>(DepotSelectActivity.this, data.getItemDatas()) {
                    @Override
                    protected void convert(ViewHolder holder, SelectDictionaryBean data) {
                        TextView name_tv = holder.getView(R.id.item_filter_tv);

                        if (data.isChecked()) {
                            name_tv.setBackgroundResource(R.drawable.rectangle_stroke_blue_bg);
                            name_tv.setTextColor(getResources().getColor(R.color.blue));
                        }
                        //
                        else {
                            name_tv.setBackgroundResource(R.drawable.rectangle_stroke_gray_bg);
                            name_tv.setTextColor(getResources().getColor(R.color.textColor));
                        }

                        holder.setText(R.id.item_filter_tv, data.getText());
                    }

                    @Override
                    protected int getItemLayoutId() {
                        return R.layout.item_filter_child;
                    }
                };

                itemAdapter.setOnItemClickListener(new OnItemClickListener<SelectDictionaryBean>() {
                    @Override
                    public void onItemClick(ViewHolder viewHolder, SelectDictionaryBean item, int position) {
                        item.setChecked(!item.isChecked());
                        itemAdapter.notifyDataSetChanged();
                    }
                });

                item_filter_rv.setLayoutManager(new GridLayoutManager(DepotSelectActivity.this, 3));
                item_filter_rv.setAdapter(itemAdapter);
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_search_filter;
            }
        };

        filter_rv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        filter_rv.setLayoutManager(new LinearLayoutManager(this));
        filter_rv.setAdapter(filterAdapter);

    }

    @OnClick({R.id.common_search_main_searchTv, R.id.common_search_main_filterLayout, R.id.btn_sure, R.id.start_time_tv, R.id.end_time_tv, R.id.btn_reset})
    public void OnClic(View v) {

        switch (v.getId()) {
            //确定
            case R.id.btn_sure:

                //搜索
            case R.id.common_search_main_searchTv:
                colectFilters();
                break;

            //重置按钮
            case R.id.btn_reset:
                //将数据变为 ，未选中状态
                for (FilterParentBean fp : filterDatas) {
                    for (SelectDictionaryBean sb : fp.getItemDatas()) {
                        if (sb.isChecked()) {
                            sb.setChecked(false);
                        }
                    }
                }

                start_time_tv.setText("");
                start_time_tv.setHint("选择开始时间");

                end_time_tv.setText("");
                end_time_tv.setHint("选择结束时间");

                break;

            case R.id.start_time_tv:

                if (startPicker == null)
                    startPicker = new TimePickerView.Builder(DepotSelectActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            start_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN).setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择起点时间")//标题文字
                            .build();

                startPicker.show();
                break;

            //结束时间
            case R.id.end_time_tv:
                if (endPicker == null)
                    endPicker = new TimePickerView.Builder(DepotSelectActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            end_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN).setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择终点时间")//标题文字
                            .build();

                endPicker.show();
                break;

            //筛选条件
            case R.id.common_search_main_filterLayout:

                boolean isSelect = (boolean) v.getTag();
                TextView filterTv = (TextView) ((ViewGroup) v).getChildAt(0);
                ImageView filterImg = (ImageView) ((ViewGroup) v).getChildAt(1);

                //选中情况下,再点是隐藏掉布局
                if (isSelect) {
                    filterTv.setTextColor(getResources().getColor(R.color.filterColor));
                    filterImg.setImageResource(R.mipmap.ic_filter);
                    filter_ly.setVisibility(View.INVISIBLE);
                    search_rv.setVisibility(View.VISIBLE);
                    sort_ly.setVisibility(View.VISIBLE);
                }
                //
                else {
                    filterTv.setTextColor(getResources().getColor(R.color.blue));
                    filterImg.setImageResource(R.mipmap.ic_filter_seleted);

                    filter_ly.setVisibility(View.VISIBLE);
                    search_rv.setVisibility(View.INVISIBLE);
                    sort_ly.setVisibility(View.GONE);

                    if (filterDatas.size() == 0) {
                        loadTypeUnitStatus();
                    }
                }

                v.setTag(!(boolean) v.getTag());
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && currentSSb != null) {

            DialogUtils.showDialog(this, "提示", "确定选择吗?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    onSureSelect();
                }
            }).show();

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 确定选择
     */
    private void onSureSelect() {
        Intent intent = new Intent();
        intent.putExtra("selectBean", currentSSb);
        this.setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 采集搜索条件
     */
    private void colectFilters() {
        //采集关键字
        keyWord = StringUtils.isCanUse(searchContentEdt.getText().toString()) ? searchContentEdt.getText().toString() : "";

        //采集非时间条件
        for (FilterParentBean fp : filterDatas) {
            for (SelectDictionaryBean sb : fp.getItemDatas()) {
                if (sb.isChecked()) {
                    if (filerMaps.containsKey(fp.getName())) {

                        //先获取之前存的值
                        String temp = filerMaps.get(fp.getName());
                        temp = temp + "," + sb.getValue();
                        filerMaps.put(fp.getName(), temp);
                    }
                    //
                    else {
                        filerMaps.put(fp.getName(), sb.getValue());
                    }
                }
            }
        }

        //采集时间条件
        if (StringUtils.isCanUse(start_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.START_TIME, start_time_tv.getText().toString());

        if (StringUtils.isCanUse(end_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.END_TIME, end_time_tv.getText().toString());

        //隐藏筛选页面
        filter_ly.setVisibility(View.INVISIBLE);
        sort_ly.setVisibility(View.VISIBLE);
        search_rv.setVisibility(View.VISIBLE);

        //调用获取数据的方法

        searchStock();
    }

    /**
     * 库存查询，注意这里必须是库存查询
     */
    private void searchStock() {
        //填充查询条件,这里有一堆数据需要填充
        SearchStockRequest searchStockRequest = new SearchStockRequest();

        searchStockRequest.customerId = "";
        searchStockRequest.factoryId = "";
        searchStockRequest.skuCode = "";
        searchStockRequest.skuId = skuId;
        searchStockRequest.skuName = "";
        searchStockRequest.whId = whId;
        searchStockRequest.stockId = "";
        searchStockRequest.stockStatus = "";
        searchStockRequest.stockType = "";
        HttpManger httpManger = HttpManger.getInstance();
        httpManger.setContext(this);

        if (stockRequest == null)
            httpManger.searchStockData(searchStockRequest);
        else
            httpManger.searchStockData(stockRequest);
        httpManger.setHttpResponseCallBackListener(new HttpManger.HttpResponseCallBackListener() {
            @Override
            public void onSuccess(BaseInfo<?> baseInfo) {

                if (baseInfo != null && baseInfo.getData() != null) {
                    resource.clear();
                    resource.addAll((ArrayList<SearchStockBean>) baseInfo.getData());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }

    /**
     * 获取 库存类型，规格，库存状态的 操作
     */
    public void loadTypeUnitStatus() {
        Observable.zip(getBaseData(AppConfig.BaseDataAction.STO_INVENTORY_STOCK_TYPE), getBasUnitList(skuId), getBaseData(AppConfig.BaseDataAction.STO_INVENTORY_STOCK_STATUS), new Function3<BaseInfo<List<SelectDictionaryBean>>, BaseInfo<List<SelectDictionaryBean>>, BaseInfo<List<SelectDictionaryBean>>, List<FilterParentBean>>() {
            @Override
            public List<FilterParentBean> apply(BaseInfo<List<SelectDictionaryBean>> listBaseInfo, BaseInfo<List<SelectDictionaryBean>> listBaseInfo2, BaseInfo<List<SelectDictionaryBean>> listBaseInfo3) throws Exception {
                FilterParentBean fp1 = new FilterParentBean("库存类型", listBaseInfo.getData());
                FilterParentBean fp2 = new FilterParentBean("规格", listBaseInfo2.getData());
                FilterParentBean fp3 = new FilterParentBean("库存状态", listBaseInfo3.getData());
                ArrayList<FilterParentBean> fpDatas = new ArrayList<>();

                fpDatas.add(fp1);
                fpDatas.add(fp2);
                fpDatas.add(fp3);

                return fpDatas;
            }
        }).subscribe(new NormalObserver<List<FilterParentBean>>() {
            @Override
            public void onNext(List<FilterParentBean> data) {
                if (data != null || data.size() > 0) {
                    filterDatas.clear();
                    filterDatas.addAll(data);
                    filterAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    /**
     * 规格查询
     *
     * @param skuId
     * @return
     */
    private Observable<BaseInfo<List<SelectDictionaryBean>>> getBasUnitList(String skuId) {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getBasUnitList(skuId).compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

    /**
     * 基础数据的Observable
     *
     * @param action
     * @return
     */

    private Observable<BaseInfo<List<SelectDictionaryBean>>> getBaseData(String action) {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getDictionaryList(action).compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

}
